package com.amt.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @Title: SocketHelper
 * @Package: com.amt.util
 * @Description: TODO(socket请求封装)
 * @Author: 江伟
 * @Date: 2020年2月月23日 14:11
 * Copyright (c) ©1994-2021 Scjydz.com All Rights Reserved.
 **/
@Slf4j
public class SocketHelper {


    /**
     * 发送socket请求
     * @param address 地址
     * @param port 端口
     * @param xmlStr 请求报文
     * @return
     * @throws Exception
     */
    public static String sendSocketRequest(String address,Integer port,String xmlStr) throws Exception {
        Socket socket = null;
        OutputStream os = null;
        InputStream is = null;

        StringBuilder sb = new StringBuilder();
        try{
            //Telnet连到到远程服务端
            socket = new Socket(address,port);
            //发送XML文档
            os = new BufferedOutputStream(socket.getOutputStream());
            byte[] information = xmlStr.getBytes("GB2312");
            os.write(information);
            os.flush();
            socket.shutdownOutput();

            //轮询5次
            for (int i = 1; i <= 5; i++){
                //线程睡眠0.5秒
                Thread.sleep(500);

                //接收XML文档
                is = socket.getInputStream();
                byte[] bytes = new byte[1024];
                int len;

                while ((len = is.read(bytes)) != -1) {
                    //注意指定编码格式，发送方和接收方一定要统一
                    sb.append(new String(bytes, 0, len,"GB2312"));
                }
                if (StringUtils.isNotEmpty(sb.toString())){
                    break;
                }
            }
        }catch (Exception e){
            log.error("请求数据：{}，socker异常：{}",xmlStr,e);
        }finally {
            //输入流和输出流必须同时关闭
            if (null != os){
                os.close();
            }
            if (null != is){
                is.close();
            }
            if (null != socket){
                socket.close();
            }
        }
        return sb.toString();
    }


}
